import type { Method } from 'axios'
import Hash from 'object-hash'

const abortRequestMap: Record<string, AbortController> = {}
/**
 * 网络请求取消能力：使用web自带的AbortController对象，兼容性良好，不兼容IE
 * @param method
 * @param request
 * @returns
 */
export function requestAbortController<Q>(method: Method, request: TRequest<Q>): TRequestAbort {
  const hash = Hash({
    method,
    ...request,
  })
  //如果存在说明还在请求中，则取消
  if (abortRequestMap[hash]) {
    abortRequestMap[hash].abort()
  }
  return {
    abort: (abortRequestMap[hash] = new AbortController()),
    finish: () => {
      delete abortRequestMap[hash]
    },
  }
}
